package com.yang.util;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;


@Service(value = "urlService")
public class UrlUtil {
 
    public JSONObject sendUrlRequest(String requestUrl){
        JSONObject jsonObject = null;
        try {
 
            URL url = new URL(requestUrl);
            //得到connection连接对象
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            //设置请求的方式
            urlConnection.setRequestMethod("GET");
            //连接
            urlConnection.connect();
            //得到响应码
            int responseCode = urlConnection.getResponseCode();
            if(responseCode == HttpURLConnection.HTTP_OK){
                //得到响应流
                InputStream inputStream = urlConnection.getInputStream();
                //获取响应的数据
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                StringBuilder content = new StringBuilder();
                String line;
                while((line = bufferedReader.readLine()) != null){
                    content.append(line);
                }
 
                jsonObject = (JSONObject) JSON.parse(content.toString());
                bufferedReader.close();
                //断开连接
                urlConnection.disconnect();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonObject;
    }
}
